package com.trace.app.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Base64;

@Slf4j
public class WechatQRCodeGenerator {
    public static void main(String[] args) {
        String appId = "wx98c8c10bfff556dc";
        String appSecret = "830d18c5df00630eba559ec7fe6d5d5f";
        String dynamicParameter = "your_dynamic_parameter";
        String pagePath = "pages/index/index";

        try {
            String accessToken = getAccessToken(appId, appSecret);
            byte[] qrCodeImage = createQRCode(accessToken, dynamicParameter, pagePath);
            // 保存或显示二维码图片
            String base64Str = Base64.getEncoder().encodeToString(qrCodeImage);
            log.info("base64:{}", base64Str);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getAccessToken(String appId, String appSecret) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            String responseBody = response.body().string();
            // 解析JSON响应，提取access_token
            // 这里可以使用JSON解析库，如Gson、Jackson等
            return responseBody;
        }
    }

    private static byte[] createQRCode(String accessToken, String dynamicParameter, String pagePath) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        String json = "{\"scene\":\"" + dynamicParameter + "\",\"page\":\"" + pagePath + "\"}";
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken).post(body).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().bytes();
        }
    }
}
